package com.pinyoumei.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.pinyoumei.component.JedisSingleClient;
import com.pinyoumei.domain.Cart;
import com.pinyoumei.mapper.TbItemMapper;
import com.pinyoumei.pojo.TbItem;
import com.pinyoumei.pojo.TbOrderItem;
import com.pinyoumei.service.CartService;
import com.pinyoumei.utils.JsonUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class CartServiceImpl implements CartService{
	
	@Autowired
	private JedisSingleClient jedisClient;
	
	@Autowired
	private TbItemMapper itemMapper;

	@Override
	public String addGoodsToCartList(@RequestParam("cartListString")String cartListString, @RequestParam("itemId")Long itemId, @RequestParam("num")Integer num) {
		log.info("#########cartList:{},itemId:{},num:{}",cartListString,itemId,num+"#########");
		//1. 根据itemId查询商品对象
		TbItem item=itemMapper.selectByPrimaryKey(itemId);
		if(item==null){
			throw new RuntimeException("商品不存在");
		}
		if(!item.getStatus().equals("1")){
			throw new RuntimeException("商品状态不合法");
		}
		//2. 根据商品对象得到商家ID
		String sellerId=item.getSellerId();
		//3. 根据商家ID在购物车列表中查询购物车对象 cartList首次为null
		List<Cart> cartList=JsonUtils.jsonToList(cartListString, Cart.class);
		Cart cart=searchCartBySellerId(cartList,sellerId);
		//4. 如果购物车列表中不存在商家的购物车
		if(cart==null){
			//4.1创建一个新的购物车对象
			cart=new Cart();
			cart.setSellerId(item.getSellerId());
			cart.setSellerName(item.getSeller());
			List<TbOrderItem> orderItemList=new ArrayList<TbOrderItem>();
			//创建新的购物车明细对象
			TbOrderItem orderItem = createOrderItem(item,num);
			orderItemList.add(orderItem);
			cart.setOrderItemList(orderItemList);
			//4.2将新的购物车对象添加到购物车列表中
			cartList.add(cart);
		}else{//5. 如果购物车列表中存在商家的购物车
			//判断商品是否已在购物车明细列表中
			TbOrderItem orderItem = searchOrderItemByItemId(cart.getOrderItemList(),itemId);
			if(orderItem==null){
				//5.1  如果不存在  ，创建新的购物车明细对象，并添加到该购物车的明细列表中
				orderItem=createOrderItem(item,num);
				cart.getOrderItemList().add(orderItem);	
			}else{
				//5.2 如果存在，在原有的数量上添加数量 ,并且更新金额	
				orderItem.setNum(orderItem.getNum()+num);//更改数量
				//金额
				orderItem.setTotalFee( new BigDecimal(orderItem.getPrice().doubleValue()*orderItem.getNum() ) );
				//当明细的数量小于等于0，移除此明细
				if(orderItem.getNum()<=0){
					cart.getOrderItemList().remove(orderItem);					
				}
				//当购物车的明细数量为0，在购物车列表中移除此购物车
				if(cart.getOrderItemList().size()==0){
					cartList.remove(cart);
				}				
			}
		}
		
		return JsonUtils.objectToJson(cartList);
	}

	/**
	 * 在购物车列表中根据商家Id查询购物车对象
	 * @param cartList
	 * @param sellerId
	 * @return
	 */
	private Cart searchCartBySellerId(List<Cart> cartList, String sellerId) {
		if(null==cartList||cartList.size()==0){
			return null;
		}else{
			for(Cart cart:cartList){
				if(cart.getSellerId().equals(sellerId)){
					return cart;
				}
			}
			return null;
		}
		
		
	}

	/**
	 * 根据skuID在购物车明细列表中查询购物车明细对象
	 * @param orderItemList
	 * @param itemId
	 * @return
	 */
	public TbOrderItem searchOrderItemByItemId(List<TbOrderItem> orderItemList,Long itemId){
		for(TbOrderItem orderItem:orderItemList){
			if(orderItem.getItemId().longValue()==itemId.longValue()){
				return orderItem;
			}			
		}
		return null;
	}
	
	/**
	 * 根据item创建购物车明细对象
	 * @param item
	 * @param num
	 * @return
	 */
	private TbOrderItem createOrderItem(TbItem item,Integer num){
		//创建新的购物车明细对象
		TbOrderItem orderItem=new TbOrderItem();
		orderItem.setGoodsId(item.getGoodsId());
		orderItem.setItemId(item.getId());
		orderItem.setNum(num);
		orderItem.setPicPath(item.getImage());
		orderItem.setPrice(item.getPrice());
		orderItem.setSellerId(item.getSellerId());
		orderItem.setTitle(item.getTitle());
		orderItem.setTotalFee(new BigDecimal(item.getPrice().doubleValue()*num) );
		return orderItem;
	}

	/**
	 * 用户登录时购物车写入redis
	 */
	@Override
	public void writeCartList2Redis(@RequestParam("cartListString")String cartListString,@RequestParam("userId")String userId) {
		String cartKey="CART:"+userId;
		jedisClient.set(cartKey, cartListString);
	}
}
